package com.lirisheng.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.lirisheng.repositories")
@EnableTransactionManagement
public class MyConfig {
    /**
     * 配置数据源
     *
     *  {@Link EmbeddedDatabaseBuilder}该类位于spring-jdbc或者spring-data-jpa,所以需要额外导入
     *
     * @return
     */
    @Bean
    public DataSource dataSource(){
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        return builder.setType(EmbeddedDatabaseType.H2).build();
    }

    /**
     *
     * 配置entityManagerFactory
     *
     * @return
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);

        // 显示sql语句
        vendorAdapter.setShowSql(true);

        LocalContainerEntityManagerFactoryBean factory =new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);

        //扫描domain(entity类的所在的包)
        factory.setPackagesToScan("com.lirisheng.domain");
        factory.setDataSource(dataSource());
        return  factory;
    }


    /**
     * 注意:在实例ioc容器的时候,需要名为transactionManager的bean作为依赖注入(但哪个bean依赖不清楚)
     * 因此,如果没有配置,则实例ioc容器的时候,就会报错
    *
     * @param entityManagerFactory
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }
}
